package com.ruc.deke.controller;

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleMultiInsertStatement.InsertIntoClause;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruc.deke.dao.DBCourseDAO;
import com.ruc.deke.dao.ExamDAO;
import com.ruc.deke.model.DBRecord;
import com.ruc.deke.model.User;
import com.ruc.deke.service.EncodingTool;
import com.ruc.deke.utils.EncryptionDecryption;
import com.ruc.deke.utils.ParseUtil;
import com.ruc.deke.utils.UUIDKit;

/**
 * 题库管理
 * 
 * @author: cyj
 * @date: 2017年9月20日 下午5:05:39
 */
@Controller
@RequestMapping(value = "/exam")
public class ExamController {

	@Resource(name = "examDAOImpl")
	private ExamDAO examDAO;

	@Resource(name = "dataSource_rucdbcourse")
	private DataSource dbDataSource;

	/**
	 * 根据moduleID获取所有题目
	 * 
	 * @param moduleId
	 *            模块号id
	 * @return
	 * @author: cyj
	 * @date: 2017年9月20日 下午5:44:14
	 */
	@RequestMapping(value = "/getExams")
	@ResponseBody
	public ArrayList<DBRecord> getExams(@RequestParam(value = "moduleId") int moduleId,HttpSession session) {
		// int moduleId = 51;
		String ano = session.getAttribute("ano").toString();
		ArrayList<DBRecord> exams = new ArrayList<DBRecord>();
		exams = examDAO.getExamsByModuleId(moduleId,ano);
		return exams;
	}

	@RequestMapping(value = "/getSelected")
	@ResponseBody
	public DBRecord getSelected(@RequestParam(value = "id") int qid) {
		// int moduleId = 51;
		DBRecord record = new DBRecord();
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;

		try {
			connection = dbDataSource.getConnection();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String sql = "select * from EXP_MODULE where QUESTIONID=" + qid;
		try {
			connection = dbDataSource.getConnection();
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<DBRecord> myStulist3 = new ArrayList<DBRecord>();
		myStulist3 = ParseUtil.toDBRecord(resultSet);
		record = myStulist3.get(0);
		return record;
	}

	/**
	 * 根据paperId获取所有题目
	 * 
	 * @param paperId
	 * @author gyh_f
	 */

	// note:之前设置value="/getQuestions" 浏览器报语法错误，原因：重名了！
	@RequestMapping(value = "/getQ")
	@ResponseBody
	public ArrayList<DBRecord> getQuestions(@RequestParam(value = "paperId") String paperId) {
		ArrayList<DBRecord> questions = new ArrayList<DBRecord>();
		questions = examDAO.getQuestionsByPaperId(paperId);
		return questions;
	}

	/*
	 * @RequestMapping(value="/getQ")
	 * 
	 * @ResponseBody public String getQuestions(String paperId){ String test =
	 * paperId; return test; }
	 */

	/**
	 * 根据teacherID获取在该教师账号下的所有试卷信息
	 * 
	 * @author gyh_f
	 * 
	 */
	@RequestMapping(value = "/getPapers")
	@ResponseBody
	public ArrayList<DBRecord> getPapers(HttpSession session, int moduleId) {
		// String teacherId = "1";
		String ano = session.getAttribute("ano").toString();
		ArrayList<DBRecord> papers = new ArrayList<DBRecord>();
		papers = examDAO.getPaperListByTeacherId(moduleId, ano);
		return papers;
	}

	/**
	 * 根据ano moduleId获取该模块下该老师的自定义题目
	 * 
	 * @author gyh_f
	 *
	 */

	/*
	 * @RequestMapping(value="/getExplistByTeacher")
	 * 
	 * @ResponseBody public ArrayList<DBRecord> getExplist(HttpSession
	 * session,int moduleId){ //String ano
	 * =session.getAttribute("ano").toString(); String ano="0000";
	 * ArrayList<DBRecord> explist = new ArrayList<DBRecord>(); explist =
	 * examDAO.getExplistByAnoAndModuleId(moduleId,ano); return explist; }
	 */

	// test

	// public Object getTimeByModule(@RequestParam(value = "moduleId") int
	// moduleId, @RequestParam(value = "userId") String userId)
	@RequestMapping(value = "/getExplistByTeacher")
	@ResponseBody
	public ArrayList<DBRecord> getExplist(HttpSession session, @RequestParam(value = "moduleId") int moduleId) {
		// public ArrayList<DBRecord> getExplist(HttpSession session, String
		// moduleId){
		//System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
		// String ano ="0000";
		String ano = session.getAttribute("ano").toString();
		//System.out.println("bnobnobno:" + ano);

		ArrayList<DBRecord> explist = new ArrayList<DBRecord>();
		explist = examDAO.getExplistByAnoAndModuleId(moduleId, ano);
		return explist;
	}
	
	//获取所选题目信息	
		@RequestMapping(value = "/getExpByTeacher")
		@ResponseBody
		public ArrayList<DBRecord> getExp(@RequestParam(value = "questionId") int questionId, @RequestParam(value = "moduleId") int moduleId) {

			ArrayList<DBRecord> explist2 = new ArrayList<DBRecord>();
			explist2 = examDAO.getExpByQuestionIdAndModuleId(questionId,moduleId);
			return explist2;
		}
		//end
	//删除所选题目
		@RequestMapping(value = "/delExpByTeacher")
		@ResponseBody
		public boolean delExp(@RequestParam(value = "questionId") int questionId, @RequestParam(value = "moduleId") int moduleId) {
			boolean t;
			t= examDAO.delExps(questionId,moduleId);
			return t;
		}
		//end
	/**
	 * 获取已选的题目，生成试卷
	 * 
	 * @author cyj
	 */
    //11.22 zk 修改
	@RequestMapping(value = "/getQuestions", method = RequestMethod.GET,produces="text/html;charset=UTF-8")
	@ResponseBody
	public Object getQuestions(HttpSession session,
			@RequestParam(value = "moduleId") int moduleId, @RequestParam(value = "qname") String qname_c,
			@RequestParam(value = "questionArr") String questionArr,@RequestParam(value = "sceneId") int sceneId) {
		/*
		  String qname = null; try { qname = new
		  String(EncryptionDecryption.decode(qname_c),"UTF-8"); } catch
		  (UnsupportedEncodingException e2) { // TODO Auto-generated catch
		  e2.printStackTrace(); }
		*/
		String qname = EncodingTool.encodeStr(qname_c);
		//System.out.println("#####"+EncodingTool.encodeStr(qname));
		//System.err.println(sceneId);
		String ano = session.getAttribute("ano").toString();
		String teacherid = session.getAttribute("teacherid").toString();
		String paperid = UUIDKit.getUUID32();

		// 获取数据库连接
		Connection dbConn = null;
		try {
			dbConn = dbDataSource.getConnection();
		} catch (SQLException e) {
			System.out.println(e.getMessage());
		}

		try {
			dbConn.setAutoCommit(false);

			insertPaperInfo(dbConn, paperid, qname, moduleId, 0, teacherid, ano,sceneId);
			for (String questionid : questionArr.split(",")) {
				//System.out.println(qname);
				insertPaperExp(dbConn, paperid, questionid);
			}
			dbConn.commit();
		} catch (SQLException e) {
			System.out.println("exception:" + e.getMessage());
			try {
				dbConn.rollback();
			} catch (SQLException e1) {
				System.out.println("exception:" + e1.getMessage());
			}
		} finally {
			try {
				dbConn.close();
			} catch (SQLException e) {
				System.out.println("exception:" + e.getMessage());
			}
		}

		return null;
	}

	/**
	 * 修改某教师某模块下的某个试卷的启用状态
	 * 
	 * @param session
	 * @param paperid
	 * @return
	 * @author: cyj
	 * @date: 2017年9月28日 下午10:00:52
	 */

	@RequestMapping(value = "/startPaper", method = RequestMethod.GET)
	@ResponseBody
	public int startUsePaper(HttpSession session,
			@RequestParam(value = "paperId") String paperId, @RequestParam(value = "moduleId") int pmoduleId) {
		// int status = 1;
		// int unstatus = -1;
		String teacherid = session.getAttribute("teacherid").toString();
		//System.out.println("paperId:" + paperId);
		int t = updatePaperInfo(teacherid,  pmoduleId, paperId);
		return t;
	}

	@RequestMapping(value = "/getScene")
	@ResponseBody
	public ArrayList<DBRecord> getScenes() {
		ArrayList<DBRecord> list = new ArrayList<DBRecord>();
		list = examDAO.getScene();
		return list;
	}

	
	//删除试卷
	@RequestMapping(value = "/deletePaper", method = RequestMethod.GET)
	@ResponseBody
	public boolean deletePaper(HttpSession session,
			@RequestParam(value = "paperId") String paperId) {
		String teacherid = session.getAttribute("teacherid").toString();
		//System.out.println("##################################");
		//System.out.println("paperId:" + paperId);
		boolean t = examDAO.delPaper(paperId,teacherid);
		return t;
	}

	/**
	 * 插入教师自定义的新题
	 * 
	 * @author gyh_f
	 */
	@RequestMapping(value = "/addExpByTeacher", method = RequestMethod.POST)
	@ResponseBody
	public boolean addExpByTeacher(HttpSession session, @RequestParam(value = "moduleId") int moduleId,
			@RequestParam(value = "edesc") String edesc, @RequestParam(value = "solution") String solution,
			@RequestParam(value = "jsonStr") String extra, @RequestParam(value = "befmoduleID") int befmoduleId,
			@RequestParam(value = "befexpID") int befexpid, @RequestParam(value = "sceneId") int sceneId) {

		// session->ano
		String ano = session.getAttribute("ano").toString();
		//System.out.println(befexpid + "======");
		//System.out.println(befmoduleId + "======");
		// define: insertNewExp(int moduleId,String edesc, String solution,
		// String extra,String ano);
		Boolean b = examDAO.insertNewExp(moduleId, edesc, solution, extra, ano, befmoduleId, befexpid,sceneId);
		return b;
	}

	/**
	 * 修改题目
	 * 
	 *
	 */
	@RequestMapping(value = "/changeExpByTeacher", method = RequestMethod.POST)
	@ResponseBody
	public boolean changeExpByTeacher(@RequestParam(value = "edesc") String edesc,@RequestParam(value = "solution") String solution,
			@RequestParam(value = "type") String type,@RequestParam(value = "questionId") int questionId) {
		//String ano = session.getAttribute("ano").toString();
		//System.out.println("#############################");
		//System.out.println(type);
		Boolean b = examDAO.changeExp(edesc,solution,type,questionId);
		return b;
	}
	// test
	/**
	 * 插入教师自定义的新题
	 * 
	 * @author gyh_f
	 */
	@RequestMapping(value = "/addExpTest", method = RequestMethod.POST)
	@ResponseBody
	public int addExpTest(HttpSession session, @RequestParam(value = "moduleId") int moduleId,
			@RequestParam(value = "edesc") String edesc, @RequestParam(value = "solution") String solution,
			@RequestParam(value = "jsonStr") String extra) {

		// session->ano
		String ano = session.getAttribute("ano").toString();
		//System.out.println(moduleId);
		//System.out.println(edesc);
		//System.out.println(solution);
		//System.out.println(extra);
		//System.out.println(ano);
		return moduleId;
	}

	// -------------------------------方法（以上为对外接口）---------------------------

	/**
	 * 向paperExp中插入题目
	 * 
	 * @param dbConn
	 * @param paperid
	 * @param questionid
	 * @return
	 */
	private String insertPaperExp(Connection dbConn, String paperid, String questionid) {
		// TODO Auto-generated method stub
		DBRecord record = new DBRecord();
		record.setField("PAPERID", "" + paperid);
		record.setField("QUESTIONID", "" + questionid);
		String result = examDAO.insertPaperExp(dbConn, record);
		return result;

	}

	/**
	 * 插入一张试卷信息
	 * 
	 * @param dbcon
	 * @param pname
	 * @param pmoduleid
	 * @param isactive
	 * @param teacherid
	 * @param ano
	 * @return
	 * @author: zk 修改：增加试卷场景
	 */
	private String insertPaperInfo(Connection dbcon, String paperid, String pname, int pmoduleid, int isactive,
			String teacherid, String ano,int sceneId) {
		// TODO Auto-generated method stub
		DBRecord record = new DBRecord();
		record.setField("PAPERID", "" + paperid);
		record.setField("PNAME", "" + pname);
		record.setField("PMODULEID", "" + pmoduleid);
		record.setField("ISACTIVE", "" + isactive);
		record.setField("TEACHERID", "" + teacherid);
		record.setField("ANO", "" + ano);
		record.setField("PSCENEID",""+ sceneId);
		String result = examDAO.insertPaperInfo(dbcon, record);
		return result;
	}

	/**
	 * 启用某个试卷
	 * 
	 * @param paperid
	 * @author: cyj
	 * @date: 2017年9月28日 下午10:10:50
	 * 
	 * @author gyh_f 做了一些更改。注意：查询分析器里不能有未commit的对该表的操作
	 * @author zk 新增试卷时删除LOGS中相应内容
	 */
	private int updatePaperInfo(String teacherid, int pmoduleId , String paperid) {
		//System.out.println(teacherid + "------------" + paperid);
		String sql2 = "update paper_info set isactive = 1 where paperid = '" + paperid + "' and teacherid = '"
				+ teacherid + "'";
		String sql1 = "update paper_info set isactive = -1 " + "where teacherid='" + teacherid + "' and isactive=1 and pmoduleid="+pmoduleId;
		//String sql3 = "update USER_EXP_STATUS set ESTATUS = 11 "+ "where userid in (select userid from  teacherid='" + teacherid + "' and isactive=1 and PMODULEID="+pmoduleId+"";
		String sql3 = "select ano from DB_COURSE_TEACHER where teacherid='" + teacherid + "'";
		//System.out.println("##"+sql3+"##");
		String sqldellog="delete from LOGS where MODULEID="+pmoduleId;
		Connection conn = null;
		Statement stmt = null;
		String sql = "";
		//System.out.println(sql1);
		//System.out.println(sql2);
		int icode1 = 1206;
		int icode2 = 1206;
		try {
			conn = dbDataSource.getConnection();
			
			conn.setAutoCommit(false);// 通知数据库开启事务(start transaction)
			stmt = conn.createStatement();
			icode1 = stmt.executeUpdate(sql1);
			//
			ResultSet rs =stmt.executeQuery(sql3);  
			ArrayList<DBRecord> records = new ArrayList<DBRecord>();
			records = ParseUtil.toDBRecord(rs);
			//System.out.println(records.get(0).getString("ANO"));//取第一列数据
			String sql4="update USER_EXP_STATUS set ESTATUS = 11 where userid in (select userid from  DB_COURSE_USER where ano='" + records.get(0).getString("ANO") + "') and MODULEID="+ pmoduleId +" ";
			//System.out.println(sqldellog);
			icode1 = stmt.executeUpdate(sql4);
			icode1 = stmt.executeUpdate(sqldellog);
			//System.err.println(icode1);
			//
			conn.commit();
			
			conn.setAutoCommit(false);// 通知数据库开启事务(start transaction)
			icode2 = stmt.executeUpdate(sql2);
			//icode2 = stmt.executeUpdate(sql3);
			conn.commit();
		} catch (SQLException e) {
			e.printStackTrace();
		}

		try {
			stmt.close();
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return icode2;
	}
	//试题场景
		@RequestMapping(value = "/getExpscene", method = RequestMethod.GET)
		@ResponseBody
		public ArrayList<DBRecord> getExpscene() {
			ArrayList<DBRecord> list = new ArrayList<DBRecord>();
			list = examDAO.getscene();
			return list;
		}
		

}
